package com.jinlejia.erp.ui.customer;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.ddm.library.DropDownMenu;
import com.freedom.yefeng.yfrecyclerview.FullyGridLayoutManager;
import com.freedom.yefeng.yfrecyclerview.YfListInterface;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.freedom.yefeng.yfrecyclerview.YfListRecyclerView;
import com.freedom.yefeng.yfrecyclerview.YfLoadMoreListener;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.CustormerAdapter;
import com.jinlejia.erp.adapter.ListDropDownAdapter;
import com.jinlejia.erp.adapter.TagsAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.common.RecycleViewDivider;
import com.jinlejia.erp.databinding.FragmentBuyingBinding;
import com.jinlejia.erp.ui.house.SearchHouseActivity;
import com.jinlejia.erp.utils.DataFilter;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 求购
 */
public class BuyingFragment extends Fragment implements YfLoadMoreListener, CompoundButton.OnCheckedChangeListener, SwipeRefreshLayout.OnRefreshListener {
    private View view;

    private String headers[] = {"位置", "意向小区", "面积", "价格", "筛选"};
    private String area[] = {"不限", "50平米以下", "50-70平米", "70-90平米", "90-110平米", "110-130平米", "130-150平米", "150-200平米", "200平米以上"};
    private String prices[] = {"不限", "80万以下", "80万-120万", "120万-150万", "150万-200万", "200万-250万", "250万-300万","300万以上"};
    private List<View> popupViews = new ArrayList<>();
    private ListDropDownAdapter areaMenuAdapter;
    private ListDropDownAdapter priceMenuAdapter;

    private CustormerAdapter adapter;
    private int page = 1;
    private boolean mLoadingLock = false;
    private ArrayList<Map<String, Object>> dataList = new ArrayList<>();
    private JSONObject jsonObject = new JSONObject();
    private int isPublic = 0;
    private TagsAdapter tagsAdapter;
    //意向星级
    private ArrayList<String> startList = new ArrayList<>();
    //居室
    private ArrayList<String> typeList = new ArrayList<>();

    private FragmentBuyingBinding binding;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_buying, container, false);
        binding = DataBindingUtil.bind(view);

        EventBus.getDefault().register(this);
        initView();
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        getData();
    }

    private void initView() {
        binding.refreshLayout.setColorSchemeResources(R.color.yellow, R.color.light_yellow);
        binding.refreshLayout.setOnRefreshListener(this);
        //地区
        final View districtView = new View(getActivity());
        //意向小区
        final View xiaoquView = new View(getActivity());
        //面积 menu
        final ListView areaView = new ListView(getActivity());
        final View squareFooter = getActivity().getLayoutInflater().inflate(R.layout.selling_square_footer, null);
        areaMenuAdapter = new ListDropDownAdapter(getActivity(), Arrays.asList(area));
        areaView.setDivider(getActivity().getResources().getDrawable(R.drawable.shape_h_line));
        areaView.addFooterView(squareFooter);
        areaView.setAdapter(areaMenuAdapter);

        //价格输入框
        final EditText leftSquare =  squareFooter.findViewById(R.id.et_left);
        final EditText rightSquare = squareFooter.findViewById(R.id.et_right);
        //重置、确定按钮
        TextView cancelSquare = squareFooter.findViewById(R.id.bt_cancel);
        TextView confirmSquare = squareFooter.findViewById(R.id.bt_confirm);

        //面积点击
        areaView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                areaMenuAdapter.setCheckItem(position);
                binding.dropDownMenu.setTabText(position == 0 ? headers[2] : area[position]);
                binding.dropDownMenu.closeMenu();
                String min = "", max = "";
                switch (position) {
                    case 1:
                        max = "50";
                        break;
                    case 2:
                        min = "50";
                        max = "70";
                        break;
                    case 3:
                        min = "70";
                        max = "90";
                        break;
                    case 4:
                        min = "90";
                        max = "110";
                        break;
                    case 5:
                        min = "110";
                        max = "130";
                        break;
                    case 6:
                        min = "130";
                        max = "150";
                        break;
                    case 7:
                        min = "150";
                        max = "200";
                        break;
                    case 8:
                        min = "200";
                        break;
                    default:
                        min = "";
                        max = "";
                        break;
                }
                jsonObject.put("orderSquareMin", min);
                jsonObject.put("orderSquareMax", max);
                page = 1;
                getData();
            }
        });
        //点击重置
        cancelSquare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                leftSquare.setText("");
                rightSquare.setText("");
            }
        });
        //确定按钮
        confirmSquare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(leftSquare.getText().toString())) {
                    Toast.makeText(getActivity(), "请输入最小面积", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(rightSquare.getText().toString())) {
                    Toast.makeText(getActivity(), "请输入最大面积", Toast.LENGTH_SHORT).show();
                } else if (Integer.parseInt(rightSquare.getText().toString()) < Integer.parseInt(leftSquare.getText().toString())) {
                    Toast.makeText(getActivity(), "最大面积必须大于最小面积", Toast.LENGTH_SHORT).show();
                } else {
                    binding.dropDownMenu.setTabText(leftSquare.getText().toString().concat("㎡-").concat(rightSquare.getText().toString()).concat("㎡"));
                    binding.dropDownMenu.closeMenu();
                    jsonObject.put("orderSquareMin", leftSquare.getText().toString());
                    jsonObject.put("orderSquareMax", rightSquare.getText().toString());
                    page = 1;
                    getData();
                }
            }
        });

        //价格区间
        final View priceAreaFooter = getActivity().getLayoutInflater().inflate(R.layout.selling_price_area_footer, null);
        final ListView priceAreaView = new ListView(getActivity());
        priceMenuAdapter = new ListDropDownAdapter(getActivity(), Arrays.asList(prices));
        priceAreaView.setDivider(getActivity().getResources().getDrawable(R.drawable.shape_h_line));
        priceAreaView.addFooterView(priceAreaFooter);
        priceAreaView.setAdapter(priceMenuAdapter);
        //价格输入框
        final EditText leftPrice = priceAreaFooter.findViewById(R.id.et_left);
        final EditText rightPrice = priceAreaFooter.findViewById(R.id.et_right);
        //重置、确定按钮
        TextView cancel = priceAreaFooter.findViewById(R.id.bt_cancel);
        TextView confirm = priceAreaFooter.findViewById(R.id.bt_confirm);

        //价格列表点击
        priceAreaView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                priceMenuAdapter.setCheckItem(position);
                binding.dropDownMenu.setTabText(position == 0 ? headers[3] : prices[position]);
                binding.dropDownMenu.closeMenu();

                String min = "", max = "";
                switch (position) {
                    case 1:
                        max = "80";
                        break;
                    case 2:
                        min = "80";
                        max = "120";
                        break;
                    case 3:
                        min = "120";
                        max = "150";
                        break;
                    case 4:
                        min = "150";
                        max = "200";
                        break;
                    case 5:
                        min = "200";
                        max = "250";
                        break;
                    case 6:
                        min = "250";
                        max = "300";
                        break;
                    case 7:
                        min = "300";
                        break;
                    default:
                        min = "";
                        max = "";
                        break;
                }
                jsonObject.put("orderPriceMin", min);
                jsonObject.put("orderPriceMax", max);
                page = 1;
                getData();

            }
        });
        //点击重置
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                leftPrice.setText("");
                rightPrice.setText("");
            }
        });
        //确定按钮
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(leftPrice.getText().toString())) {
                    Toast.makeText(getActivity(), "请输入最低价格", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(rightPrice.getText().toString())) {
                    Toast.makeText(getActivity(), "请输入最高价格", Toast.LENGTH_SHORT).show();
                } else if (Integer.parseInt(rightPrice.getText().toString()) < Integer.parseInt(leftPrice.getText().toString())) {
                    Toast.makeText(getActivity(), "最高价格必须大于最低价格", Toast.LENGTH_SHORT).show();
                } else {
                    binding.dropDownMenu.setTabText(leftPrice.getText().toString().concat("万-").concat(rightPrice.getText().toString()).concat("万"));
                    binding.dropDownMenu.closeMenu();
                    jsonObject.put("orderPriceMin", leftPrice.getText().toString());
                    jsonObject.put("orderPriceMax", rightPrice.getText().toString());
                    page = 1;
                    getData();
                }
            }
        });

        // 添加到view List
        popupViews.add(districtView);
        popupViews.add(xiaoquView);
        popupViews.add(areaView);
        popupViews.add(priceAreaView);
        popupViews.add(getFilterView());


        TextView contentView = new TextView(getActivity());
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0));
        contentView.setGravity(Gravity.CENTER);
//        contentView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);

        //init dropdownview
        binding.dropDownMenu.setDropDownMenu(Arrays.asList(headers), popupViews, contentView);
        binding.dropDownMenu.setOnMenuChangeListener(new DropDownMenu.OnMenuChangeListener() {
            @Override
            public void onMenuChange(int menuID) {
                if (menuID == 0) {
                    //地区
                    startActivityForResult(new Intent(getActivity(), LocationActivity.class), 100);
                } else if (menuID == 2) {
                    //意向小区
                    Intent sIntent = new Intent(getActivity(), SearchHouseActivity.class);
                    sIntent.putExtra("type", "select");
                    startActivityForResult(sIntent, 200);
                }
            }
        });

        binding.rvHouseList.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.rvHouseList.setHasFixedSize(true);
        adapter = new CustormerAdapter(dataList,"万");
        adapter.changeMode(YfListMode.MODE_LOADING);
        binding.rvHouseList.setAdapter(adapter);
        binding.rvHouseList.addItemDecoration(new RecycleViewDivider(
                getActivity(), LinearLayoutManager.VERTICAL, 2, getResources().getColor(R.color.colorDivider)));
        binding.rvHouseList.enableAutoLoadMore(this);
        adapter.setOnItemClickListener(new YfListInterface.OnItemClickListener() {
            @Override
            public void onItemClick(View view, Object o) {
                Map<String, Object> map = (Map<String, Object>) o;
                Intent intent = new Intent(getActivity(), DetailCustomerActivity.class);
                intent.putExtra("csCode", map.get("csCode").toString());
                intent.putExtra("type", "sale");
                intent.putExtra("name", map.get("name").toString());
                intent.putExtra("sex", map.get("sex").toString());
                startActivity(intent);
            }
        });

    }

    private View getFilterView() {
        getTags();
        View view = getActivity().getLayoutInflater().inflate(R.layout.customer_filter_layout, null);
        //公私客
        ((RadioGroup) view.findViewById(R.id.radio_group)).setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.customer_private:
                        isPublic = 0;
                        break;
                    case R.id.customer_public:
                        isPublic = 1;
                        break;
                    default:
                        isPublic = 0;
                        break;
                }
            }
        });
        //关注
        ((CheckBox) view.findViewById(R.id.my_attention)).setOnCheckedChangeListener(this);
        ((CheckBox) view.findViewById(R.id.star1)).setOnCheckedChangeListener(this);
        ((CheckBox) view.findViewById(R.id.star2)).setOnCheckedChangeListener(this);
        ((CheckBox) view.findViewById(R.id.star3)).setOnCheckedChangeListener(this);
        ((CheckBox) view.findViewById(R.id.star4)).setOnCheckedChangeListener(this);
        ((CheckBox) view.findViewById(R.id.star5)).setOnCheckedChangeListener(this);
        ((CheckBox) view.findViewById(R.id.type1)).setOnCheckedChangeListener(this);
        ((CheckBox) view.findViewById(R.id.type2)).setOnCheckedChangeListener(this);
        ((CheckBox) view.findViewById(R.id.type3)).setOnCheckedChangeListener(this);
        ((CheckBox) view.findViewById(R.id.type4)).setOnCheckedChangeListener(this);
        ((CheckBox) view.findViewById(R.id.type5)).setOnCheckedChangeListener(this);

        YfListRecyclerView recyclerView = (YfListRecyclerView) view.findViewById(R.id.yf_recycler);
        recyclerView.setLayoutManager(new FullyGridLayoutManager(getActivity(), 4, GridLayoutManager.VERTICAL, false));
        ArrayList<String> data = new ArrayList<>();
        tagsAdapter = new TagsAdapter(data);
        recyclerView.setAdapter(tagsAdapter);

        view.findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(String.valueOf(isPublic) ,"TAG_GET_PUBLIC");
                jsonObject.put("tags", tagsAdapter.getSelectStr());
                //意向
                StringBuilder sb = new StringBuilder();
                for (String s : startList) {
                    sb = sb.append(";").append(s);
                }
                jsonObject.put("level", sb.toString().replaceFirst(";", ""));
                //居室
                StringBuilder sbT = new StringBuilder();
                for (String s : typeList) {
                    sbT = sbT.append(";").append(s);
                }
                jsonObject.put("orderHouseType", sbT.toString().replaceFirst(";", ""));
                jsonObject.put("isPublic", isPublic);
                StringBuilder sb1 = new StringBuilder();
                if (isPublic == 0) {
                    sb1 = sb1.append("私客");
                } else {
                    sb1 = sb1.append("公客");
                }
                if (jsonObject.getIntValue("isAttention") == 1) {
                    sb1 = sb1.append("我关注的房源");
                }
                sb1 = sb1.append(sb.toString().replaceFirst(";", ""));
                sb1 = sb1.append(tagsAdapter.getSelectStr());
                if (TextUtils.isEmpty(sb1.toString())) {
                    binding.dropDownMenu.setTabText("筛选");
                } else {
                    binding.dropDownMenu.setTabText(sb1.toString().substring(0,2).concat("..."));
                }
                binding.dropDownMenu.closeMenu();
                page = 1;
                getData();
            }
        });

        return view;
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.my_attention:
                if (isChecked) {
                    jsonObject.put("isAttention", 1);
                } else {
                    jsonObject.put("isAttention", 0);
                }
                break;
            case R.id.star1:
                if (isChecked) {
                    startList.add("e");
                } else {
                    startList.remove("e");
                }
                break;
            case R.id.star2:
                if (isChecked) {
                    startList.add("d");
                } else {
                    startList.remove("d");
                }
                break;
            case R.id.star3:
                if (isChecked) {
                    startList.add("c");
                } else {
                    startList.remove("c");
                }
                break;
            case R.id.star4:
                if (isChecked) {
                    startList.add("b");
                } else {
                    startList.remove("b");
                }
                break;
            case R.id.star5:
                if (isChecked) {
                    startList.add("a");
                } else {
                    startList.remove("a");
                }
                break;
            case R.id.type1:
                if (isChecked) {
                    typeList.add("1");
                } else {
                    typeList.remove("1");
                }
                break;
            case R.id.type2:
                if (isChecked) {
                    typeList.add("2");
                } else {
                    typeList.remove("2");
                }
                break;
            case R.id.type3:
                if (isChecked) {
                    typeList.add("3");
                } else {
                    typeList.remove("3");
                }
                break;
            case R.id.type4:
                if (isChecked) {
                    typeList.add("4");
                } else {
                    typeList.remove("4");
                }
                break;
            case R.id.type5:
                if (isChecked) {
                    typeList.add("5");
                } else {
                    typeList.remove("5");
                }
                break;
            default:
                break;
        }
    }

    /**
     * 获取tag列表
     */
    private void getTags() {
        OkHttpUtils.get()
                .url(ApiConfig.TAGS_LIST)
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(getActivity(), response)) {
                            JSONArray data = JSON.parseArray(response.get("data").toString());
                            //数据列表
                            ArrayList<String> tagList = JSON.parseObject(data.toString(), new TypeReference<ArrayList<String>>() {
                            });
                            tagsAdapter.setData(tagList);
                        }
                    }
                });
    }

    private void getData() {
        mLoadingLock = true;
        jsonObject.put("pageSize", 20);
        jsonObject.put("pageIndex", page);
        jsonObject.put("isPublic", isPublic);
        OkHttpUtils.postString()
                .url(ApiConfig.SALE_CUSTOMER_LIST)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(getActivity(), response, adapter)) {
                            JSONArray data = JSON.parseArray(response.get("data").toString());
                            //数据列表
                            ArrayList<Map<String, Object>> list = JSON.parseObject(data.toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            if (page == 1) {
                                adapter.setData(list);
                            } else {
                                adapter.addData(list);
                            }
                        } else if (response.get("code").toString().equals("303")) {
                            //没有更多
                            page--;
                        }
                        if (binding.refreshLayout.isRefreshing()) {
                            binding.refreshLayout.setRefreshing(false);
                        }
                        mLoadingLock = false;
                    }
                });
    }

    @Override
    public void loadMore() {
        if (adapter.getData().size() % 20 == 0) {
            if (mLoadingLock) {
                return;
            }
            mLoadingLock = true;
            page++;
            adapter.addFooter("loading");

            getData();
        }else if( adapter.getData().size() > 10 ){
            adapter.addFooter(R.string.is_all);
        }
    }

    @Override
    public void onRefresh() {
        page = 1;
        getData();
    }

    @Subscriber(tag = "TAG_SEARCH_SHS")
    public void searchFilter(String data) {
        page = 1;
        jsonObject.put("name", data);
        getData();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case 100:
                    String txt = data.getStringExtra("countyName") + "-" + data.getStringExtra("districtname");
                    if (txt.equals("-")) {
                        binding.dropDownMenu.setTabText("地区");
                    } else {
                        binding.dropDownMenu.setTabText(txt);
                    }
                    binding.dropDownMenu.closeMenu();
                    jsonObject.put("orderCounty", data.getStringExtra("countyName"));
                    jsonObject.put("orderArea", data.getStringExtra("districtname"));
                    page = 1;
                    getData();
                    break;
                case 200:
                    jsonObject.put("enjoyEstate", data.getStringExtra("name"));
                    page = 1;
                    binding.dropDownMenu.setTabText(TextUtils.isEmpty(data.getStringExtra("name")) ? headers[1] : data.getStringExtra("name"));
                    binding.dropDownMenu.closeMenu();
                    getData();
                    break;
                default:
                    break;
            }

        }else if( resultCode == Activity.RESULT_CANCELED ){
            binding.dropDownMenu.closeMenu();
        }
    }

}
